package com.studentstreet;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.studentstreet.adapter.GoodsItemAdapter;
import com.studentstreet.component.AbstractCommonActivity;
import com.studentstreet.component.LoadStateView;
import com.studentstreet.component.LwtAlertDialog;
import com.studentstreet.component.LwtAlertDialog.Builder;
import com.studentstreet.entities.GoodsEntity;
import com.studentstreet.tools.HttpHelper;
import com.studentstreet.tools.PreferenceTools;
import com.studentstreet.tools.SortById;
import com.studentstreet.tools.SortByName;
import com.studentstreet.tools.SortByPrice;
import com.studentstreet.tools.SortBySaleCount;
import com.studentstreet.tools.Util;
import com.studentstreet.tools.dbhelper.GoodsDBHelper;

/**
 * @author likebamboo
 * 
 */
public class GoodsActivity extends AbstractCommonActivity implements
		AdapterView.OnItemClickListener {
	// 商品列表控件
	private ListView goodsList;
	// 商品列表适配器
	private GoodsItemAdapter adapter;
	// LoadStateView是一个自写的组件，继承于RelativeLayout，可实现不同状态的布局
	private LoadStateView loadStateView;
	// 商品信息Json数据
	private String goodsJson = "";
	// 从上一个Activity传来的参数，商家ID和Name
	private int sellerId = 0;
	private String sellerName = "";
	// Title标题
	private TextView titleText;
	// Login Button登录按钮
	private Button login_bt;
	// 头部左边的按钮
	private ImageButton backImgBt = null;
	// 商品实体列表
	private List<GoodsEntity> goodsEntityList = null;
	// 排序按钮
	private Button sortButton = null;
	// 回到顶部按钮
	private Button goTopButton = null;
	// 向服务器发送请求的标志
	private String action_flag = "get_hot_goods";
	// 标识发送message的属性。
	private static final int REFRESH_LIST = 0x10001;
	private static final int SHOW_LOAD_STATE_VIEW = 0x10003;
	private static final int HIDE_LOAD_STATE_VIEW = 0x10004;
	private static final int LIST_IS_EMPTY = 0x10005;
	// 标志排序方式的三个属性， 按名称、价格、销售量排序
	private final int SORT_BY＿NAME = 1;
	private final int SORT_BY＿PRICE = 2;
	private final int SORT_BY＿SALE_COUTN = 3;
	// 标识所选择的排序方式的
	int CHECKED_ITEM = 0;
	// 用于获得用户数据操作
	PreferenceTools prefTools = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.goods);
		// 将当前Activity压入堆栈中
		MyApp.getInstance().addActivity(this);
		prefTools = new PreferenceTools(this);
		// 获得上个Activity传来的参数
		Intent intent = getIntent();
		// 取得intent带来的数据
		sellerId = intent.getIntExtra("seller_id", 0);
		sellerName = intent.getStringExtra("seller_name");
		// sellerId=0 表示这是“众口味”界面
		if (sellerId == 0) {
			// 去掉布局的头部，以免重复
			LinearLayout header = (LinearLayout) findViewById(R.id.header);
			header.setVisibility(View.GONE);
		} else {
			// 表示这是通过点击某个商家过来的
			action_flag = "get_seller_goods";
			// 返回按钮
			backImgBt = (ImageButton) findViewById(R.id.header_imgBt);
			// 头部中间的标题
			titleText = (TextView) findViewById(R.id.title);
			// 登录按钮
			login_bt = (Button) findViewById(R.id.login_bt);
			// 返回按钮
			backImgBt.setImageResource(R.drawable.back);
			backImgBt.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					finish();
				}
			});
			// 头部中间的标题
			titleText.setText(sellerName);
			// 登录按钮
			login_bt.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					// 显示登录对话框
					Intent intent = new Intent(GoodsActivity.this,
							LoginDialog.class);
					startActivityForResult(intent, RESULT_FIRST_USER);
				}
			});
		}

		// 初始化布局
		// 商品列表
		goodsList = (ListView) findViewById(R.id.goodsList);
		// 适配器
		adapter = new GoodsItemAdapter(this, goodsList);
		// 包含从开始加载到列表显示的整个布局
		loadStateView = (LoadStateView) findViewById(R.id.downloadStatusBox);
		// 排序按钮
		sortButton = (Button) findViewById(R.id.goods_sortButton);
		// 返回顶部按钮
		goTopButton = (Button) findViewById(R.id.goods_gotop);

		// 排序
		sortButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// 显示排序对话框
				showSortDialog();
			}
		});

		// 回到顶部
		goTopButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (goodsEntityList.size() != 0) {
					goodsList.requestFocusFromTouch();
					goodsList.setSelection(0);
				}
			}
		});

		// 设置 "重新加载" 监听器
		loadStateView.setOnReloadClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				reload();
			}
		});
		// 设置商品列表的适配器
		goodsList.setAdapter(adapter);
		goodsList.setOnItemClickListener(this);
		// 加载商品列表
		reload();
	}

	// 加载商品类别
	private void reload() {
		// 先清空适配器
		adapter.clean();
		// 开始加载，此时会显示ProgressBar，隐藏 “重新加载” 按钮
		loadStateView.startLoad();
		// 加载列表线程
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					// 使用apache HTTP客户端实现
					String urlStr = Util.BASE_URL + "/servlet/GoodsServlet";
					// 创建网络连接工具对象
					HttpHelper helper = new HttpHelper(urlStr);
					// 添加参数
					// 动作标记
					helper.addParam("action_flag", action_flag);
					// 商品名
					helper.addParam("sellerId", sellerId + "");
					// 获得服务器返回的数据
					goodsJson = helper.getResponse();
					if ("".equals(goodsJson)) {
						sendMessage(LIST_IS_EMPTY);
						return;
					}
					// 让线程休眠，可以看到旋转的ProgressBar
					Thread.sleep(1 * 500);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}

				// 将下载的Json数据填充到Adapter中
				loadData();
				// 发送一个消息，通知adapter，列表中的数据有更新
				sendMessage(REFRESH_LIST);
			}
		}).start();
	}

	// 将下载的Json数据转化为 GoodsEntity列表，并填充到适配器adapter中
	public void loadData() {
		if ("".equals(goodsJson)) {
			return;// 应从本地数据库读，暂时不实现；
		}
		// 将数据保存到数据库
		GoodsDBHelper dbHelper = new GoodsDBHelper(this);

		dbHelper.saveToDB(goodsJson);
		// 设置adapter
		Type listType = new TypeToken<ArrayList<GoodsEntity>>() {
		}.getType();
		// 创建Gson 对象
		Gson gson = new Gson();
		// 将Json数据转化为List<GoodsEntity>
		goodsEntityList = gson.fromJson(goodsJson, listType);
		// 如果是“总口味”则按照商品的销售数量排序
		if (action_flag.equals("get_hot_goods")) {
			Collections.sort(goodsEntityList, new SortBySaleCount());
			CHECKED_ITEM = 3;
		}
		// 把商品图片路径补充完整
		for (GoodsEntity goods : goodsEntityList) {
			goods.setImageUrl(Util.BASE_GOODS_IMG_URL + goods.getImageUrl());
		}
		adapter.addGoods(goodsEntityList);
	}

	@Override
	protected void onResume() {
		super.onResume();
		PreferenceTools prefTools = new PreferenceTools(this);
		// 判断是否已经登录
		// 没有登录或者是从 众口味 界面过来的都不改变
		if (!prefTools.isLogin() || action_flag.equals("get_hot_goods")) {
			return;
		}
		// 登录后修改登录按钮上的text
		String userName = prefTools.getUserName();
		if (!userName.equals("")) {
			login_bt.setText(userName);
			// 去掉登录按钮文本右边的图标
			login_bt.setCompoundDrawablesWithIntrinsicBounds(null, null, null,
					null);
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			// 当在订单详情界面将商品添加到收藏夹后，更新本界面相应Item的图标
			RelativeLayout view = (RelativeLayout) goodsList
					.getChildAt(requestCode);
			if (view != null) {
				Button favor = (Button) view
						.findViewById(R.id.goods_add_favorite);
				favor.setBackgroundResource(R.drawable.favorite_s);
			}
		}
	}

	// 排序
	public void sort(int sortField) {
		adapter.clean();
		switch (sortField) {
		case SORT_BY＿NAME:
			Collections.sort(goodsEntityList, new SortByName());
			break;
		case SORT_BY＿PRICE:
			Collections.sort(goodsEntityList, new SortByPrice());
			break;
		case SORT_BY＿SALE_COUTN:
			Collections.sort(goodsEntityList, new SortBySaleCount());
			break;
		default:
			Collections.sort(goodsEntityList, new SortById());
			break;
		}
		adapter.addGoods(goodsEntityList);
		sendMessage(REFRESH_LIST);
	}

	// 显示排序列表
	private void showSortDialog() {
		final Builder builder = new LwtAlertDialog.Builder(this);
		LwtAlertDialog dialog;
		builder.setTitle(getResources().getString(R.string.sort_method))
				.setIcon(android.R.drawable.ic_dialog_info)
				.setSingleChoiceItems(
						new String[] {
								getResources().getString(R.string.sort_default),
								getResources().getString(R.string.sort_byName),
								getResources().getString(R.string.sort_byPrice),
								getResources().getString(
										R.string.sort_bySaleCount) },
						CHECKED_ITEM, new LwtAlertDialog.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								switch (which) {
								case SORT_BY＿NAME:// 按名称排序
									if (CHECKED_ITEM == SORT_BY＿NAME) {// 如果当前的排序正是所选的，则什么都不做
										dialog.dismiss();
										return;
									}
									sort(SORT_BY＿NAME);
									CHECKED_ITEM = SORT_BY＿NAME;
									dialog.dismiss();
									break;
								case SORT_BY＿PRICE:// 按价格排序
									if (CHECKED_ITEM == SORT_BY＿PRICE) {// 如果当前的排序正是所选的，则什么都不做
										dialog.dismiss();
										return;
									}
									sort(SORT_BY＿PRICE);
									CHECKED_ITEM = SORT_BY＿PRICE;
									dialog.dismiss();
									break;
								case SORT_BY＿SALE_COUTN:// 按销售量排序
									if (CHECKED_ITEM == SORT_BY＿SALE_COUTN) {// 如果当前的排序正是所选的，则什么都不做
										dialog.dismiss();
										return;
									}
									sort(SORT_BY＿SALE_COUTN);
									CHECKED_ITEM = SORT_BY＿SALE_COUTN;
									dialog.dismiss();
									break;
								default:// 默认排序
									if (CHECKED_ITEM == 0) {// 如果当前的排序正是所选的，则什么都不做
										dialog.dismiss();
										return;
									}
									sort(0);
									CHECKED_ITEM = 0;
									dialog.dismiss();
									break;
								}
							}
						});
		dialog = (LwtAlertDialog) builder.create();
		// 显示对话框
		dialog.show();
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		Intent intent = new Intent(GoodsActivity.this,
				GoodsDetailActivity.class);
		GoodsEntity goods = goodsEntityList.get(arg2);
		Bundle bundle = new Bundle();
		bundle.putParcelable("goods", goods);
		intent.putExtra("goods_detail", bundle);
		startActivityForResult(intent, arg2);
	}

	@Override
	protected void handleOtherMessage(int flag) {
		switch (flag) {
		case REFRESH_LIST:
			// 更新列表
			adapter.notifyDataSetChanged();
			// 加载完成，让ProgressBar消失
			loadStateView.stopLoad();
			// 如果列表为空，显示提示信息
			if (adapter.getCount() == 0) {
				loadStateView.showEmpty();
			}
			break;
		case SHOW_LOAD_STATE_VIEW:
			loadStateView.startLoad();
			break;
		case HIDE_LOAD_STATE_VIEW:
			loadStateView.stopLoad();
			break;
		case LIST_IS_EMPTY:
			// 让ProgressBar消失
			loadStateView.stopLoad();
			loadStateView.showError();
			break;
		default:
			Toast.makeText(GoodsActivity.this,
					getResources().getString(R.string.network_error),
					Toast.LENGTH_SHORT).show();
			break;
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (sellerId == 0 && keyCode == KeyEvent.KEYCODE_BACK) {
			MyApp.getInstance().exit(this);
		}
		return super.onKeyDown(keyCode, event);
	}
}
